<template>
    <div>
        <el-card class="card-primary" shadow="hover">
            <!--头部-->
            <div slot="header" style="text-align: right">
                <el-upload action="/api/cms/asset"
                           ref="upload"
                           multiple
                           :data="parameter"
                           :headers = "headers"
                           :show-file-list="false"
                           :on-error="uploadFailedCallback"
                           :before-upload="handleBeforeUpload"
                           :on-success="uploadSuccessCallback"
                >
                    <el-button v-waves  icon="el-icon-upload"  type="primary"> 添加新素材</el-button>
                </el-upload>
            </div>
            <el-row :gutter="20" style="min-height:650px"    v-loading="stateManager.listLoading">
            <el-col :span="24" >
                    <!--图片列表-->
                <div class="row asset-container">
                    <template v-for="(item,index) in tableList.items">


                    <div class="col-xl-2 col-lg-2 col-md-3 col-sm-6">
                        <div class="single-cat-item">
                            <img :src="item.path"alt="">
                            <div class="item-meta">
                                <span> <h4>{{item.name}} </h4> </span>
                                <i class="el-icon-edit-outline" @click="showEditDialog(item.id)"></i>
                                <i class="el-icon-delete"  @click="deleteItem(item.id)"></i>
                                <p>上传于{{item.created_at}}</p>
                                <span class="watch-list-btn" v-for="item in item.tags">{{item}}</span>
                            </div>
                        </div>
                    </div>
                    </template>
                </div>
                <!--分页-->
            </el-col>
            </el-row>
            <div class="pagination-container">
                <div class="col">
                    <el-pagination
                        background
                        layout="prev, pager, next,total"
                        :page-size="18"
                        :total="list.total"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage">
                    </el-pagination>
                </div>
            </div>
        </el-card>
        <el-dialog :stateManager="stateManager"></el-dialog>
    </div>
</template>

<script>
  import _dialog from './_dialog.vue'
  import { getToken } from '@/utils/auth'
  import waves from '@/directive/waves' // Waves directive
  export default {
    name: 'asset',
    components: {
      'el-dialog': _dialog
    },
    directives: { waves },
    data: function () {
      return {
        list: this.$listDataSource({
          url: '/api/cms/asset',
        }),
        model: this.$modelDataSource({
          url: '/api/cms/asset',
          dataKey: 'model',
          attributes: {
            id: 0,
            tags: [],
          }
        }),
        pageTitle: '素材管理',
        imgIndex: 0,
        currentPage: 1,
        parameter: {
          type: 'all',
          tags: ''
        },
        stateManager: {
          refreshList: true,
          editDialogVisible: false,
          editModelId: null,
          listLoading: true,
          buttonLoading: false,
        },
        headers:{},
        query: {
          page: 1,
          type: '',
          tags: [],
        },
      //  点击退出变量
        isShow: false,
      }
    },
    created () {
      this.$store.commit('app/setPageTitle', '素材管理')
      this.headers['Authorization'] ='Bearer '+ getToken()
    },
    methods: {
      showEditDialog: function (id) {
        this.stateManager.editDialogVisible = true
        this.stateManager.editModelId = id
        this.stateManager.buttonLoading = false
      },
      uploadSuccessCallback: function (response, file) {
        let self = this
        //上传成功回调
        this.$message({
          message: '成功上传',
          type: 'success'
        })
        this.stateManager.refreshList = true
      },
      uploadFailedCallback: function (error, file) {
        //上传失败回调
        this.$message.error('上传失败')
      },
      // 翻页
      handleCurrentChange (val) {
        this.currentPage = val
        this.query.page = val
        this.stateManager.refreshList = true
      },

      // 删除
      deleteItem (itemId) {
        let self = this
        this.$confirm('确认删除吗，删除后不可恢复', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          title: '删除确认'
        }).then(() => {
          self.model.uuid = itemId
          self.model.destroy(function () {
            self.stateManager.refreshList = true
            self.$message.success('删除成功')
          }, function (error) {
            self.$message.error(error.response.data.state)
          })
        })
      },
      handleBeforeUpload (file) {
        let isJPG
        switch(file.type) {
          case  'image/jpeg':
          case  'image/jpg':
          case  'image/png':
            isJPG = true
            break;
          default:
            isJPG = false
        }
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
    },
    computed: {
      tableList () {
        let self = this
        if (this.stateManager.refreshList) {
          this.stateManager.listLoading = true
          this.$store.dispatch('cms/fetchTags')
          this.list.fetch(self.query, function () {
            self.stateManager.refreshList = false
            self.stateManager.listLoading = false
          })
        }
        return this.list
      }
    }
  }
</script>
